/*AyflEomXWyqCHfdTxzWda+bKRNxqoRhrf02Huevr4hQ=*/
//主子表卡片
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createPage, ajax, base, toast, high, print, cardCache, getMultiLang } from 'nc-lightapp-front';
import { buttonClick, initTemplate, afterEvent, pageInfoClick } from './events';
import {
	buttonVisible,
	getButtonsKey,
	dealTranferBtns,
	initCardBodyEditControl,
	onSelectedCardBodyEditControl,
	initCardBodybrowseControl
} from '../../../public/components/pubUtils/buttonvisible.js';
import { tableId, formId, billType, nodekey, dataSource, pkname, linkPageId } from './constants';
import { bodyBeforeEvent } from '../../../public/components/pubUtils/arapTableRefFilter';
import { formBeforeEvent } from '../../../public/components/pubUtils/arapFormRefFilter';
import linkSourceCard from '../../../public/components/linkSourceCard.js';
import { dealCardData } from '../../../public/components/pubUtils/dealCardData';
import {cardSocketConnect,cardSocketErrorFlag,toggleBtnStatus,throwSagaErrorAgency} from '../../../public/components/pubUtils/MicroServiceSocket.js';
const { BillTrack, PrintOutput } = high;
import NCUploader from 'uap/common/components/NCUploader';
let { NCBackBtn, NCDiv, NCAffix } = base;
let {
	setDefData,
	getDefData,
	addCache,
	getNextId,
	deleteCacheById,
	getCacheById,
	updateCache,
	getCurrentLastId
} = cardCache;

class Card extends Component {
	constructor(props) {
		super(props);
		this.state = {
			showBillTrack: false, //控制单据追溯是否显示
			showUploader: false, //附件
			target: null,
			json: {}
		};
		this.printData = {
			billtype: billType, //单据类型
			appcode: props.getSearchParam('c'), //功能节点编码，即模板编码
			nodekey: props.getSearchParam('p'), //模板节点标识  =交易类型
			oids: [this.props.getUrlParam('id')], // 功能节点的数据主键 oids含有多个元素(['1001A41000000000A9LR','1001A410000000009JDD'])时为批量打印,
			userjson: billType //单据类型,billtype不是必需字段，后台没有设置接收字段，以userjson代替
		};
		this.outputData = {
			billtype: billType, //单据类型
			appcode: props.getSearchParam('c'),
			funcode: props.getSearchParam('c'),
			nodekey: props.getSearchParam('p'), //模板节点标识  =交易类型
			oids: [this.props.getUrlParam('id')], // 功能节点的数据主键
			userjson: billType, //单据类型
			outputType: 'output'
		};
		this.formId = formId;
		this.tableId = tableId;
		this.billType = billType;
		this.pkname = pkname;
		this.Info = {
			allButtonsKey: [],
			isModelSave: false //是否是整单保存，默认为false
		};
		this.dataInSaga = {    //用于saga里面的busiinfo
			appcode: props.getSearchParam('c') ? props.getSearchParam('c') : null,
			pagecode: props.getSearchParam('p') ? props.getSearchParam('p') : null,
			butncode: null
		}
		this.billinfo ={
			billtype:'card',
			pagecode:props.getSearchParam('p') ? props.getSearchParam('p') : null,
			headcode:formId,
			bodycode:tableId}
		props.use.form(formId);
		props.use.cardTable(tableId);
	}

	componentWillReceiveProps(nextProps) { }
	componentDidMount() {
		let callback = (json) => {
			this.setState({ json: json }, () => {
				window.onbeforeunload = () => {
					let status = this.props.getUrlParam('status');
					if (status == 'edit' || status == 'add') {
						return '';
					}
				};
				this.props.setRelationItemBillinfo(this.billinfo);
				initTemplate.call(this, this.props, this.initShow);
			});
		};
		getMultiLang({ moduleId: ['payablebill', 'public'], domainName: 'arap', currentLocale: 'simpchn', callback });
	}

	getPagecode = () => {
		let pagecode = this.props.getUrlParam('pagecode');
		if (!pagecode) {
			pagecode = this.props.getSearchParam('p');
		}
		return pagecode;
	};

	// 附件的关闭点击
	onHideUploader = () => {
		this.setState({
			showUploader: false
		});
	};

	//页面初始化
	initShow = () => {
		if (this.props.getUrlParam('scene') && this.props.getUrlParam('scene') == 'fip') {
			linkSourceCard(
				this.props,
				linkPageId,
				'pk_estipayablebill',
				this.formId,
				this.tableId,
				pkname,
				dataSource,
				this
			);
		} else if (!this.props.getUrlParam('status')) {
			this.toggleShow();
		} else if (this.props.getUrlParam('status') != 'add') {
			ajax({
				url: '/nccloud/arap/estipayablebill/querycard.do',
				data: { pk_bill: this.props.getUrlParam('id') },
				success: (res) => {
					this.props.beforeUpdatePage(); //打开开关
					if (res.data) {
						updateCache(pkname, this.props.getUrlParam('id'), res.data, this.formId, dataSource);
						if (res.data.head) {
							this.props.form.setAllFormValue({ [this.formId]: res.data.head[this.formId] });
						}
						if (res.data.body) {
							this.props.cardTable.setTableData(this.tableId, res.data.body[this.tableId]);
						}
					}

					let status = this.props.getUrlParam('status');
					this.props.cardTable.setStatus(this.tableId, status);
					this.props.form.setFormStatus(this.formId, status);
					throwSagaErrorAgency.call(this,res)
					this.props.updatePage(this.formId, this.tableId); //关闭开关
					this.props.setUrlParam({ pagecode: res.data.head[this.formId].rows[0].values.pk_tradetype.value });
					this.toggleShow(res);
				}
			});
		}
	};

	//切换页面状态
	toggleShow = (res) => {
		if(res){
			toggleBtnStatus.call(this,res,'card_head');
		}
		let status = this.props.getUrlParam('status');
		if (!status) {
			status = 'browse';
		} //如果未定义，默认给值浏览态
		let trueBtn = []; //可见的按钮
		let falseBtn = []; //不可见的按钮
		for (let i = 0; i < this.Info.allButtonsKey.length; i++) {
			let flag = buttonVisible(
				status,
				this.props.createMasterChildData(this.getPagecode(), this.formId, this.tableId).head[this.formId]
					.rows[0].values,
				this.Info.allButtonsKey[i],
				'card',
				this
			);
			if (flag) {
				trueBtn.push(this.Info.allButtonsKey[i]);
			} else {
				falseBtn.push(this.Info.allButtonsKey[i]);
			}
		}
		//初始化肩部按钮信息增行等按钮的控制
		if (status == 'browse') {
			initCardBodybrowseControl(this);
		}
		this.props.button.setButtonVisible(trueBtn, true);
		this.props.button.setButtonVisible(falseBtn, false);
		if (status != 'browse') {
			this.props.cardPagination.setCardPaginationVisible('cardPaginationBtn', false);
			this.props.BillHeadInfo.setBillHeadInfoVisible({ showBackBtn: false });
		} else {
			this.props.cardPagination.setCardPaginationVisible('cardPaginationBtn', true);
			this.props.BillHeadInfo.setBillHeadInfoVisible({ showBackBtn: true });
		}
		//利润中心，责任核算要素相关字段不可以编辑
		let keys=['pk_pcorg_v','pk_pcorg','checkelement'];
		this.props.cardTable.setColEditableByKey(this.tableId, keys, true);
		this.props.form.setFormItemsDisabled(this.formId,{'pk_pcorg_v':true,'pk_pcorg':true,'checkelement':true})
	};
	//卡片表体点击行事件
	onSelected = () => {
		onSelectedCardBodyEditControl(this);
	};

	//挂起操作和取消挂起的操作
	pause = (url) => {
		let selectedData = this.props.cardTable.getCheckedRows(this.tableId);
		if (selectedData.length == 0) {
			toast({ color: 'success', content: this.state.json['payablebill-000030'] }); /* 国际化处理： 请至少选择一条子表数据*/
			return;
		}
		let pauseObj = [];
		selectedData.forEach((val) => {
			pauseObj.push(val.data.values.pk_estipayableitem.value);
		});
		let data = {
			pk_items: pauseObj,
			pk_bill: this.props.getUrlParam('id'),
			ts: this.props.form.getFormItemsValue(this.formId, 'ts').value,
			pageId: this.getPagecode(),
			billType: this.billType
		};
		ajax({
			url: url,
			data: Object.assign(data,this.dataInSaga),
			success: (res) => {
				if (res.data.message) {
					toast({
						duration: 'infinity',
						color: res.data.PopupWindowStyle,
						content: res.data.message
					});
				} else {
					toast({ color: 'success', content: this.state.json['payablebill-000031'] }); /* 国际化处理： 操作成功*/
				}
				if (res.data.billCard) {
					if (res.data.billCard.head) {
						this.props.form.setAllFormValue({ [this.formId]: res.data.billCard.head[this.formId] });
					}
					if (res.data.billCard.body) {
						this.props.cardTable.setTableData(this.tableId, res.data.billCard.body[this.tableId]);
					}
					let newCardData = this.props.createMasterChildData(this.getPagecode(), this.formId, this.tableId);
					updateCache(pkname, this.props.getUrlParam('id'), newCardData, this.formId, dataSource);
				}
				this.onSelected();
			}
		});
	};

	//保存单据
	saveBill = () => {

		let result=this.props.validatePageToToast([
			{
				name: this.formId,
				type: "form",
			},
			{
				name: this.tableId,
				type: "cardTable",
			}
		]);
		if(result&&!result.allPassed){
			return;
		}
		let cardData = this.props.createMasterChildData(this.getPagecode(), this.formId, this.tableId);
		let newCardData = dealCardData(this, cardData); //去掉空值，减少压缩时间
		let datas = {
			cardData: newCardData,
			uiState: this.props.getUrlParam('status')
		};
		let callback = () => {
			ajax({
				url: '/nccloud/arap/arappub/save.do',
				data: Object.assign(datas,this.dataInSaga),
				success: (res) => {
					let pk_estipayablebill = null;
					let pk_tradetype = null;
					if (res.success) {
						if (res.data) {
							toast({
								color: 'success',
								content: this.state.json['payablebill-000014']
							}); /* 国际化处理： 保存成功*/
							this.props.beforeUpdatePage(); //打开开关
							if (res.data.head) {
								this.props.form.setAllFormValue({ [this.formId]: res.data.head[this.formId] });
								pk_estipayablebill = res.data.head[this.formId].rows[0].values.pk_estipayablebill.value;
								pk_tradetype = res.data.head[this.formId].rows[0].values.pk_tradetype.value;
							}
							if (res.data.body) {
								this.props.cardTable.updateDataByRowId(this.tableId, res.data.body[this.tableId]);
							}
						}
						this.props.cardTable.setStatus(this.tableId, 'browse');
						this.props.form.setFormStatus(this.formId, 'browse');
						this.props.updatePage(this.formId, this.tableId); //关闭开关
						let newCardData = this.props.createMasterChildData(
							this.getPagecode(),
							this.formId,
							this.tableId
						);
						updateCache(pkname, pk_estipayablebill, newCardData, this.formId, dataSource); //修改之后更新缓存
						this.props.setUrlParam({ status: 'browse', id: pk_estipayablebill });
					}

					if (this.Info.isModelSave) {
						this.Info.isModelSave = false;
						this.props.cardTable.closeModel(this.tableId);
					}
					this.toggleShow(res);
				}
			});
		};

		this.props.validateToSave(datas.cardData, callback, { table1: 'cardTable' }, 'card');
	};

	//获取列表肩部信息
	getTableHead = (buttons) => {
		return (
			<span>
				{this.props.button.createButtonApp({
					area: 'card_body',
					buttonLimit: 3,
					onButtonClick: buttonClick.bind(this),
					popContainer: document.querySelector('.header-button-area')
				})}
			</span>
		);
	};

	//打印
	onPrint = () => {
		this.printData.oids = [this.props.getUrlParam('id')];
		this.printData.nodekey = this.props.form.getFormItemsValue(this.formId, 'pk_tradetype').value;
		print(
			'pdf', //支持两类: 'html'为模板打印, 'pdf'为pdf打印
			'/nccloud/arap/arappub/print.do', //后台服务url
			this.printData,
			false
		);
	};

	//正式打印
	officalPrintOutput = () => {
		this.printData.oids = [this.props.getUrlParam('id')];
		this.printData.nodekey = this.props.form.getFormItemsValue(this.formId, 'pk_tradetype').value;
		ajax({
			url: '/nccloud/arap/arappub/officialPrint.do',
			data: this.printData,
			async: false,
			success: (res) => {
				if (res.success) {
					print(
						'pdf', //支持两类: 'html'为模板打印, 'pdf'为pdf打印
						'/nccloud/arap/arappub/print.do', //后台服务url
						this.printData,
						false
					);
				}
			}
		});
	};
	//取消正式打印
	cancelPrintOutput = () => {
		this.printData.oids = [this.props.getUrlParam('id')];
		this.printData.nodekey = this.props.form.getFormItemsValue(this.formId, 'pk_tradetype').value;
		ajax({
			url: '/nccloud/arap/arappub/cancelPrint.do',
			data: this.printData,
			success: (res) => {
				if (res.success) {
					//取消正式打印提示框
					toast({ color: 'success', content: res.data });
				}
			}
		});
	};

	cancel = () => {
		//取消按钮
		if (this.props.getUrlParam('status') === 'edit') {
			this.props.setUrlParam({ status: 'browse' });
			this.props.beforeUpdatePage(); //打开开关
			let id = this.props.getUrlParam('id');
			let cardData = getCacheById(id, dataSource);
			if (cardData) {
				this.props.form.EmptyAllFormValue(this.formId);
				this.props.cardTable.setTableData(this.tableId, { rows: [] });
				this.props.form.setAllFormValue({ [this.formId]: cardData.head[this.formId] });
				this.props.cardTable.setTableData(this.tableId, cardData.body[this.tableId]);
				this.props.cardTable.setStatus(this.tableId, 'browse');
				this.props.form.setFormStatus(this.formId, 'browse');
				this.props.updatePage(this.formId, this.tableId); //关闭开关
				this.toggleShow();
			} else {
				this.initShow();
			}
		}
	};

	pubajax = (url) => {
		ajax({
			url: url,
			data: Object.assign({
				pk_bill: this.props.getUrlParam('id'),
				ts: this.props.form.getFormItemsValue(this.formId, 'ts').value,
				pageId: this.getPagecode(),
				billType: this.billType
			},this.dataInSaga),
			success: (res) => {
				if (res.data) {
					toast({ color: 'success', content: this.state.json['payablebill-000031'] }); /* 国际化处理： 操作成功*/
					if (res.data.head) {
						this.props.form.setAllFormValue({ [this.formId]: res.data.head[this.formId] });
					}
					if (res.data.body) {
						this.props.cardTable.updateDataByRowId(this.tableId, res.data.body[this.tableId]);
					}
					let newCardData = this.props.createMasterChildData(this.getPagecode(), this.formId, this.tableId);
					updateCache(pkname, this.props.getUrlParam('id'), newCardData, this.formId, dataSource);
					this.toggleShow(res);
				}
			}
		});
	};

	//打印输出
	printOutput = () => {
		this.outputData.oids = [this.props.getUrlParam('id')];
		this.outputData.nodekey = this.props.form.getFormItemsValue(this.formId, 'pk_tradetype').value;
		this.refs.printOutput.open();
	};
	//输出成功回调函数
	onSubmit() { }

	//整单保存事件
	modelSaveClick = () => {
		this.Info.isModelSave = true;
		this.saveBill();
	};

	//返回列表
	backList = () => {
		this.props.pushTo('/list', {
			pagecode: '200805EPB_LIST'
		});
	};

	render() {
		let { cardTable, form, button, modal, cardPagination } = this.props;
		const { createBillHeadInfo } = this.props.BillHeadInfo;
		let buttons = this.props.button.getButtons();
		let multiLang = this.props.MutiInit.getIntl(this.moduleId);
		let { createForm } = form;
		let { createCardTable } = cardTable;
		const { createCardPagination } = cardPagination;
		let { createButton } = button;
		let { createModal } = modal;
		let { showUploader, target } = this.state;

		return (
			<div className="nc-bill-card">
				<div className="nc-bill-top-area">
					<NCAffix offsetTop={0}>
						<NCDiv areaCode={NCDiv.config.HEADER} className="nc-bill-header-area">
							<div className="header-title-search-area">
								{createBillHeadInfo({
									title: this.state.json['payablebill-000032'],
									backBtnClick: () => {
										this.backList();
									}
								})}
							</div>
							{/* 国际化处理： 暂估应付单管理*/}
							<div className="header-button-area">
								{cardSocketConnect.call(this,'card_head',dataSource)}
								{cardSocketErrorFlag.call(this,'card_head')}
								{this.props.button.createButtonApp({
									area: 'card_head',
									buttonLimit: 3,
									onButtonClick: buttonClick.bind(this),
									popContainer: document.querySelector('.header-button-area')
								})}
								<div className="header-cardPagination-area" style={{ float: 'right' }}>
									{createCardPagination({
										handlePageInfoChange: pageInfoClick.bind(this),
										dataSource: dataSource
									})}
								</div>
							</div>
						</NCDiv>
					</NCAffix>
					<div className="nc-bill-form-area">
						{createForm(this.formId, {
							fieldid: "estipayablebill",
							onAfterEvent: afterEvent.bind(this),
							onBeforeEvent: formBeforeEvent.bind(this)
						})}
					</div>
				</div>
				<div className="nc-bill-bottom-area">
					<div className="nc-bill-table-area">
						{createCardTable(this.tableId, {
							fieldid: "estipayablebill",
							tableHead: this.getTableHead.bind(this, buttons),
							modelSave: this.modelSaveClick.bind(this),
							hideAdd: true,
							hideDel: true,
							onAfterEvent: afterEvent.bind(this),
							onBeforeEvent: bodyBeforeEvent.bind(this),
							onSelected: this.onSelected.bind(this),
							onSelectedAll: this.onSelected.bind(this),
							showCheck: true,
							showIndex: true,
							adaptionHeight: true,high_selectable: {
								enable: true  //默认为true
							},
							// 框选
							onBatchSelected: (...params) => {
								this.onSelected.call(this)
							},
						})}
					</div>
				</div>

				{/* {单据追溯} */}
				<BillTrack
					show={this.state.showBillTrack}
					close={() => {
						this.setState({ showBillTrack: false });
					}}
					pk={this.props.getUrlParam('id')} //单据id
					type={
						this.props.form.getFormItemsValue(this.formId, 'pk_tradetype') ? (
							this.props.form.getFormItemsValue(this.formId, 'pk_tradetype').value
						) : null
					} //单据类型
				/>
				{/* {打印输出} */}
				<PrintOutput
					ref="printOutput"
					url="/nccloud/arap/arappub/outPut.do"
					data={this.outputData}
					callback={this.onSubmit}
				/>
				{showUploader && (
					<NCUploader
						billId={
							this.props.form.getFormItemsValue(this.formId, 'pk_estipayablebill') ? (
								this.props.form.getFormItemsValue(this.formId, 'pk_estipayablebill').value
							) : null
						}
						billNo={
							this.props.form.getFormItemsValue(this.formId, 'billno') ? (
								this.props.form.getFormItemsValue(this.formId, 'billno').value
							) : null
						}
						childAppcode={this.props.getSearchParam('c')} 
						childPagecode={this.getPagecode()}
						target={target}
						placement={'bottom'}
						onHide={this.onHideUploader}
					/>
				)}
			</div>
		);
	}
}

Card = createPage({
	orderOfHotKey: [formId, tableId],//区域快捷键切换支持
	mutiLangCode: '2052',
})(Card);

export default Card;

/*AyflEomXWyqCHfdTxzWda+bKRNxqoRhrf02Huevr4hQ=*/